//
//  THAlertView.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 BaseBusiness. All rights reserved.
//

#import "THAlertView.h"
#import "THAlertContentView.h"
#import "THAlertCommonViewController.h"
#import "THAlertViewManager.h"
#import "THImageAlertContentView.h"

 

@interface THAlertView ()<UIGestureRecognizerDelegate,THAlertContentViewDelegate>
@property (nonatomic, assign)BOOL isSelect;//是否勾选不再提醒
@property (nonatomic, assign)BOOL isValid;
@property (nonatomic, assign)BOOL isShowing;
@property (nonatomic, strong)UIWindow *window;
@property (nonatomic, strong)UIViewController *viewController;
@property (nonatomic, strong)UIView *view;
@property (nonatomic, strong)UIView *backgroundView;
@property (nonatomic, strong)THAlertContentView *contentView;
@property (nonatomic, strong)THImageAlertContentView *imgContentView;

@property (nonatomic, copy) THAlertViewHandler actionHandler;
@property (nonatomic, copy) THAlertViewHandler cancelHandler;

@property (nonatomic, copy)NSAttributedString *attrStr;
@property (nonatomic, copy)NSString *iconStr;
@property (nonatomic, copy)NSString *title;
@property (nonatomic, copy)NSString *desc;
@property (nonatomic, copy)NSString *sureBtnTitle;
@property (nonatomic, copy)NSString *cancelBtnTitle;
@property (nonatomic, copy)NSString *selectTitle;


@property (nonatomic, assign) BOOL isJLAlert;

@end

@implementation THAlertView

- (nonnull instancetype)initWithTitle:(nullable NSString *)title
                                 desc:(nullable NSString *)desc
                         sureBtnTitle:(nullable NSString *)sureBtnTitle
                        actionHandler:(THAlertViewHandler)actionHandler
{
    if (self = [super init]) {
        self.title = title;
        self.desc  = desc;
        self.sureBtnTitle = sureBtnTitle;
        self.actionHandler = actionHandler;
        [self setupDefaults];
        [self configeSubViews];
        
    }
    return self;
}

- (nonnull instancetype)initWithTitle:(nullable NSString *)title
                             descAttr:(nullable NSAttributedString *)desc
                         sureBtnTitle:(nullable NSString *)sureBtnTitle
                        actionHandler:(THAlertViewHandler)actionHandler
{
    if (self = [super init]) {
        self.title = title;
        self.attrStr  = desc;
        self.sureBtnTitle = sureBtnTitle;
        self.actionHandler = actionHandler;
        [self setupDefaults];
        [self configeSubViews];
        
    }
    return self;
}



- (nonnull instancetype)initWithTitle:(nullable NSString *)title
                                    desc:(nullable NSString *)desc
                            sureBtnTitle:(nullable NSString *)sureBtnTitle
                          cancelBtnTitle:(nullable NSString *)cancelBtnTitle
                           actionHandler:(THAlertViewHandler)actionHandler
                           cancelHandler:(THAlertViewHandler)cancelHandler
{
    if (self = [super init]) {
        self.title = title;
        self.desc  = desc;
        self.sureBtnTitle = sureBtnTitle;
        self.cancelBtnTitle = cancelBtnTitle;
        self.actionHandler = actionHandler;
        self.cancelHandler = cancelHandler;
        [self setupDefaults];
        [self configeSubViews];
    }
    return self;
}

- (nonnull instancetype)initWithTitle:(nullable NSString *)title
                                    desc:(nullable NSString *)desc
                            sureBtnTitle:(nullable NSString *)sureBtnTitle
                          cancelBtnTitle:(nullable NSString *)cancelBtnTitle
                             selectTitle:(nullable NSString *)selectTitle
                           actionHandler:(THAlertViewHandler)actionHandler
                           cancelHandler:(THAlertViewHandler)cancelHandler
{
    if (self = [super init]) {
        self.title = title;
        self.desc  = desc;
        self.sureBtnTitle = sureBtnTitle;
        self.cancelBtnTitle = cancelBtnTitle;
        self.selectTitle = selectTitle;
        self.actionHandler = actionHandler;
        self.cancelHandler = cancelHandler;
        [self setupDefaults];
        [self configeSubViews];
    }
    return self;
}

- (nonnull instancetype)initImgTypeWithImgStr:(nullable NSString *)imgStr
                                        title:(nullable NSString *)title
                                         desc:(nullable NSString *)desc
                                      attrStr:(nullable NSAttributedString *)attrStr
                               cancelBtnTitle:(nullable NSString *)cancelBtnTitle
                                 sureBtnTitle:(nullable NSString *)sureBtnTitle
                                actionHandler:(THAlertViewHandler)actionHandler
                                cancelHandler:(THAlertViewHandler)cancelHandler;
{
    if (self = [super init]) {
        self.iconStr = imgStr;
        self.title = title;
        self.desc  = desc;
        self.attrStr = attrStr;
        self.cancelBtnTitle = cancelBtnTitle;
        self.sureBtnTitle = sureBtnTitle;
        self.actionHandler = actionHandler;
        self.cancelHandler = cancelHandler;
        [self setupDefaults];
        [self configeImgSubViews];
    }
    return self;
}

#pragma mark - 透明样式
- (nonnull instancetype)initDarkStyleTitle:(nullable NSString *)title
                                    desc:(nullable NSString *)desc
{
    if (self = [super init]) {
        [self setupDefaults];
        self.contentView = [[UIView alloc]init];
        self.contentView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        self.contentView.layer.cornerRadius = kSizeRateTo(8);
        
        UILabel *titleLab = UILabel.new;
        titleLab.font = kFontMedium(18);
        titleLab.textColor = [UIColor whiteColor];
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.numberOfLines = 0;
        titleLab.text = title;
        [self.contentView addSubview:titleLab];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(0);
            make.top.equalTo(30);
            make.left.greaterThanOrEqualTo(20);
        }];
        
        UILabel *contentLab = UILabel.new;
        contentLab.font = kFontMedium(16);
        contentLab.textColor = [UIColor whiteColor];
        contentLab.textAlignment = NSTextAlignmentCenter;
        contentLab.numberOfLines = 0;
        contentLab.text = desc;
        [self.contentView addSubview:contentLab];

        [contentLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(0);
            make.top.equalTo(titleLab.mas_bottom).offset(15);
            make.left.greaterThanOrEqualTo(20);
            make.bottom.equalTo(-90);
        }];
        
        UIButton *sure = UIButton.new;
        
        [sure setTitle:@"我知道了" forState:UIControlStateNormal];
        [sure setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        sure.titleLabel.font = kFontMedium(16);
        sure.layer.cornerRadius = 8;
        sure.layer.masksToBounds = YES;
        sure.layer.borderColor = [[UIColor whiteColor] CGColor];
        sure.layer.borderWidth = 1;
        [sure addTarget:self action:@selector(dimiss) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:sure];
        [sure mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(0);
            make.width.equalTo(244);
            make.height.equalTo(50);
            make.bottom.equalTo(-20);
        }];
        
        [self.view addSubview:self.contentView];
        [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.view);
            make.width.mas_equalTo(305);
        }];
    }
    return self;
}

 
- (nonnull instancetype)initJLImgTypeWithImgStr:(nullable NSString *)imgStr
                                        title:(nullable NSString *)title
                                         desc:(nullable NSString *)desc
                                      attrStr:(nullable NSAttributedString *)attrStr
                               cancelBtnTitle:(nullable NSString *)cancelBtnTitle
                                 sureBtnTitle:(nullable NSString *)sureBtnTitle
                                actionHandler:(THAlertViewHandler)actionHandler
                                cancelHandler:(THAlertViewHandler)cancelHandler
{
    if (self = [super init]) {
        self.iconStr = imgStr;
        self.title = title;
        self.desc  = desc;
        self.attrStr = attrStr;
        self.cancelBtnTitle = cancelBtnTitle;
        self.sureBtnTitle = sureBtnTitle;
        self.actionHandler = actionHandler;
        self.cancelHandler = cancelHandler;
        self.isJLAlert = YES;
        [self setupDefaults];
        [self configeImgSubViews];
    }
    return self;
}

- (void)setupDefaults
{
    self.backgroundAlpha = 0.1;
    
    self.view = [UIView new];
    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    self.view.userInteractionEnabled = NO;
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    self.backgroundView = [[UIVisualEffectView alloc] initWithEffect:nil];
    self.backgroundView.alpha = self.backgroundAlpha;
    self.backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.backgroundView];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelAction:)];
    tapGesture.delegate = self;
    [self.backgroundView addGestureRecognizer:tapGesture];
    

    THAlertCommonViewController *viewController = [[THAlertCommonViewController alloc] init];
    viewController.statusBarHidden = [UIApplication sharedApplication].statusBarHidden;
    viewController.statusBarStyle  = [UIApplication sharedApplication].statusBarStyle;
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    if ([UIDevice currentDevice].systemVersion.intValue == 9) {
        self.window.windowLevel = CGFLOAT_MAX;
    } else {
        self.window.windowLevel = UIWindowLevelAlert;
    }
    self.window.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.window.opaque = NO;
    self.window.backgroundColor = UIColor.clearColor;
    
    self.window.rootViewController = viewController;
    self.view.frame = self.window.frame;
    [viewController.view addSubview:self.view];

}

- (void)configeSubViews
{
    self.contentView = [[THAlertContentView alloc]init];
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.contentView.layer.cornerRadius = kSizeRateTo(20);
    self.contentView.layer.masksToBounds = YES;
    self.contentView.delegate = self;
    self.contentView.title = self.title;
    self.contentView.desc  = self.desc;
    if(self.attrStr){
        self.contentView.descAttr = self.attrStr.copy;
    }

    self.contentView.sureBtnTitle = self.sureBtnTitle;
    self.contentView.cancelBtnTitle = self.cancelBtnTitle;
    self.contentView.selectTitle = self.selectTitle;
    self.contentView.btnVerticalDirection = self.btnVerticalDirection;
    [self.contentView configViews];
    [self.view addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.width.mas_equalTo(kSizeRateTo(280));
    }];
}

- (void)configeImgSubViews
{
    self.imgContentView = [[THImageAlertContentView alloc]init];
    self.imgContentView.backgroundColor = [UIColor whiteColor];
    self.imgContentView.delegate = self;
    self.imgContentView.title = self.title;
    self.imgContentView.desc  = self.desc;
    self.imgContentView.sureBtnTitle = self.sureBtnTitle;
    self.imgContentView.cancelBtnTitle = self.cancelBtnTitle;
    self.imgContentView.iconStr = self.iconStr;
    self.imgContentView.attributedString = self.attrStr;
    self.imgContentView.isJLStyle = self.isJLAlert;
    [self.imgContentView configViews];
    [self.view addSubview:self.imgContentView];
    [self.imgContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view.mas_centerY).offset(-kStatusBarHeight);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(kSizeRateTo(280));
    }];
}

- (void)zh_alertContentViewDelegate_sureEvent
{
    self.isSelect = self.contentView.isSelect;
    
    [self dimiss];
    if (_actionHandler) {
        _actionHandler(self);
    }
}

- (void)zh_alertContentViewDelegate_cancelEvent
{
    self.isSelect = self.contentView.isSelect;
    [self dimiss];
    if (_cancelHandler) {
        _cancelHandler(self);
    }
}


- (void)show
{
//    if (!self.isValid || self.isShowing) return;
    if(self.isShowing) return;
    self.isShowing = YES;
    self.view.userInteractionEnabled = NO;
    self.window.hidden = NO;
    
    UIWindow *keyWindow = [THCurrentVCWindowsManager shareManager].currentWindow;
    [keyWindow endEditing:YES];
    [self.window makeKeyAndVisible];
    self.view.userInteractionEnabled = YES;
    //绑定当前的object,防止被释放,后期有更好的方案 可以进行修改
    [[THAlertViewManager shareManager] bindAlertViewWith:self];
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    animation.values = @[@(0.8), @(1.05), @(1.1), @(1)];
    animation.keyTimes = @[@(0), @(0.3), @(0.5), @(1.0)];
    animation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear], [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear], [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear], [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    animation.duration = .28;
    if (self.contentView) {
        [self.contentView.layer addAnimation:animation forKey:@"bounce"];
    }else if (self.imgContentView){
        [self.imgContentView.layer addAnimation:animation forKey:@"bounce"];
    }
}

- (void)dimiss
{
    self.isShowing = NO;
    self.window.hidden = YES;
    self.view = nil;
    self.viewController = nil;
    self.window = nil;
        //解绑当前的object,使其释放,后期有更好的方案 可以进行修改
    [[THAlertViewManager shareManager] deleteAlertViewWith:self];
//    [UIView animateWithDuration:.3 animations:^{
//        self.view.alpha = 0;
//        self.contentView.transform = CGAffineTransformMakeScale(.4, .4);
//    }completion:^(BOOL finished) {
//        
//    }];
}

- (void)cancelAction:(UIButton *)sender
{
   
    [self dimiss];
    if (_cancelHandler) {
        _cancelHandler(self);
    }
}
 
- (void)showComplete{
}

 

- (void)setBackgroundAlpha:(CGFloat)backgroundAlpha{
    _backgroundAlpha = backgroundAlpha;
    self.backgroundView.alpha = backgroundAlpha;
}
- (void)setIsBgCanClose:(BOOL)isBgCanClose
{
    _isBgCanClose = isBgCanClose;
    self.backgroundView.userInteractionEnabled = isBgCanClose;
    
}
- (void)dealloc
{
    NSLog(@"被释放.....");
}


#pragma mark - 竖排按钮弹窗
- (nonnull instancetype)initWithTitle:(nullable NSString *)title
                                 desc:(nullable NSString *)desc
                 verticleSureBtnTitle:(nullable NSString *)sureBtnTitle
               verticleCancelBtnTitle:(nullable NSString *)cancelBtnTitle
                        actionHandler:(THAlertViewHandler)actionHandler
                        cancelHandler:(THAlertViewHandler)cancelHandler
{
    if (self = [super init]) {
        self.title = title;
        self.desc  = desc;
        self.sureBtnTitle = sureBtnTitle;
        self.cancelBtnTitle = cancelBtnTitle;
        self.actionHandler = actionHandler;
        self.cancelHandler = cancelHandler;
        self.btnVerticalDirection = YES;
        [self setupDefaults];
        [self configeSubViews];
    }
    return self;
}

@end
